import { getUserInfo, login, getUserDetailById } from '@/api/user'
// 引入封装好的Cookies函数
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  // 尝试从本地Cookies中取出
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  steToken(state, data) {
    // 数据持久化
    setToken(data)
    state.token = data
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录
  async login(store, data) {
    const res = await login(data)
    store.commit('steToken', res)
    // 主动介入token失效校验条件一, 需要记录登录成功时间
    localStorage.setItem('tokenTime', Date.now())
  },

  // 获取用户详情
  async getUserInfo(store) {
    const res = await getUserInfo()
    // 根据id获取员工基本信息
    const data = await getUserDetailById(res.userId)
    store.commit('setUserInfo', { ...res, ...data })
  },

  // 退出登录
  loginOut(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
